package com.service;

import com.dao.MiaoshaUserDao;
import com.domain.MiaoshaUser;
import com.exception.GlobalException;
import com.redis.MiaoshaUserKey;
import com.redis.RedisService;
import com.result.CodeMsg;
import com.sun.org.apache.bcel.internal.classfile.Code;
import com.util.MD5Util;
import com.util.UUIDUtil;
import com.vo.LoginVo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;


/**
 * @author lvcaihong
 * @dtae 2019/2/15 11:05
 */
@Service
public class MiaoshaUserService {
    private static final Logger logger = LoggerFactory.getLogger(MiaoshaUserService.class);
    @Autowired
    private MiaoshaUserDao miaoshaUserDao;
    @Autowired
    private RedisService redisService;

    public MiaoshaUser getById(Long id){
        return miaoshaUserDao.getById(id);
    }


    public boolean login(LoginVo loginVo) {
        if(loginVo == null){
            //return CodeMsg.SERVER_ERROR;
            throw  new GlobalException(CodeMsg.SERVER_ERROR);
        }
        String formPass = loginVo.getPassword();
        String mobile = loginVo.getMobile();
        //判断手机号是否存在
        MiaoshaUser miaoshaUser = getById(Long.parseLong(mobile));
        if(miaoshaUser == null){
            throw new GlobalException(CodeMsg.MOBILE_NOT_EXIST);
        }
        //验证密码
        //获取数据库中的密码
        String dbPass = miaoshaUser.getPassword();
        logger.info("数据库中的密码：{}",dbPass);
        //获取数据库中的salt
        String saltDB = miaoshaUser.getSalt();
        String calcPass = MD5Util.formPassToDBPass(formPass,saltDB);
        logger.info("计算出的密码：{}",calcPass);
        //判断数据库中的密码和计算出的密码是否一致
        if(!calcPass.equals(dbPass)){
            throw new GlobalException(CodeMsg.PASSWORD_ERROR);
        }
        //生成cookie
        String token = UUIDUtil.uuid();
        //token写到cookie中，传递到客户端（标记token对应的是哪一个用户,将用户信息写到redis中）
        //闹到token，即可找到对应的user
        redisService.set(MiaoshaUserKey.token,token,miaoshaUser);
        return true;
    }
}
